<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

class View
{
    public $request;
    protected $_config;
    protected $_engine;

    public function __construct($request = null) {
        $this->request = $request;
        $this->_config = Loader::loadConfig('view');

        Loader::loadThirdPart('Smarty', 'class', 'Smarty');

        $this->_engine = new Smarty();
        $this->_engine->setTemplateDir($this->_config['templates']);
        $this->_engine->setCompileDir($this->_config['templates_c']);
        $this->_engine->setPluginsDir($this->_config['plugins_dir']);
    }

    public function getEngine() {
        return $this->_engine;
    }

    public function __set($key, $val) {
        $this->_engine->assign($key, $val);
    }

    public function __get($key) {
        return $this->_engine->get_template_vars($key);
    }

    public function __isset($key) {
        return $this->_engine->get_template_vars($key) !== null;
    }

    public function __unset($key) {
        $this->_engine->clear_assign($key);
    }

    public function assign($spec, $value = null) {
        if (is_array($spec)) {
            $this->_engine->assign($spec);
            return;
        }

        $this->_engine->assign($spec, $value);
    }

    public function clearVars() {
        $this->_engine->clear_all_assign();
    }

    public function render($name, $mod = '') {
        if('' == $mod) {
            $mod = $this->request->get_module();
        }

        $name = ($mod == 'wogu' ? '' : $mod . DIRECTORY_SEPARATOR) . $name . $this->_config['template_ext'];
        return $this->_engine->fetch(strtolower($name));
    }

    public function display($name, $mod = '') {
        if('' == $mod) {
            $mod = $this->request->get_module();
        }

        $name = ($mod == 'wogu' ? '' : $mod . DIRECTORY_SEPARATOR) . $name . $this->_config['template_ext'];
        $this->_engine->display($name);
    }
}